<template>
  <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" :fullscreen.sync="fullscreen"
    @cancel="handleCancel" :footer="null">
    <a-spin :spinning="submitLoading">
      <a-card :bordered="false">
        <template #title>
          <a-button type="primary" html-type="submit" @click="doSign" :disabled="!(model.bizStatus === 1)"> 签收 </a-button>
          <a-button type="danger" ghost html-type="submit" @click="doRefuse" style="margin-left:15px" :disabled="!(model.bizStatus === 1)"> 驳回 </a-button>
        </template>
        <detail-list title="单据信息">
          <detail-list-item term="返货状态">
            <!-- 状态：0已保存 1已提交（已返货） 2已签收 3已签收待确认 4已确认  -->
            <a-tag color="blue" v-if="model.bizStatus === 0">新建</a-tag>
            <a-tag color="orange" v-if="model.bizStatus === 1">待签收</a-tag>
            <a-tag color="blue" v-if="model.bizStatus === 2">已签收</a-tag>
            <a-tag color="blue" v-if="model.bizStatus === 3">待确认</a-tag>
            <a-tag color="blue" v-if="model.bizStatus === 4">已确认</a-tag>
          </detail-list-item>
          <detail-list-item term="单号">{{ model.billNo }}</detail-list-item>
          <detail-list-item term="返货门店">{{ model.orgName }}/{{ model.shopName }}</detail-list-item>
          <detail-list-item term="收银员姓名">{{ model.clerkUserName }}</detail-list-item>
          <detail-list-item term="返货时间">{{ model.bizDate }}</detail-list-item>
          <detail-list-item term="发货备注">{{ model.deliveryRemark ? model.deliveryRemark : '-' }}</detail-list-item>
          <detail-list-item term="签收时间">{{ model.signDate ? model.signDate : '-' }}</detail-list-item>
        </detail-list>
        <a-divider style="margin: 15px 0" />
        <detail-list title="商品价值">
          <detail-list-item term="商品总件数">{{ (model.bizStatus === 3 || model.bizStatus === 4) ?
              model.adjustTotalQty : model.totalQty
          }}</detail-list-item>
          <detail-list-item term="商品总金额(元)">{{ (model.bizStatus === 3 || model.bizStatus === 4) ?
              model.adjustTotalAmount : model.totalAmount
          }}</detail-list-item>
        </detail-list>
        <!-- 明细 -->
        <a-card style="margin-top: -15px" :bordered="false" :tabList="tabList" :activeTabKey="activeTabKey" @tabChange="
          (key) => {
            this.activeTabKey = key
          }
        ">

          <!-- 增加价位表格 -->
          <div class="table-operations">
            <a-row>
              <a-col :md="20" :xs="24">
                <a-button type="primary" @click="newRow" :disabled="model.bizStatus !== 1">添加商品</a-button>
              </a-col>
              <a-col :md="4" :xs="24" class="r-group">
                <a-radio-group v-model="groupCol">
                  <a-radio-button value="default">默认</a-radio-button>
                  <a-radio-button value="price">价位</a-radio-button>
                </a-radio-group>
              </a-col>
            </a-row>
          </div>
          <a-table v-if="groupCol == 'default'" size="middle" rowKey="id" :columns="goodsColumns"
            :dataSource="detailRespList" :pagination="false">
            <span slot="photo" slot-scope="text">
              <a-avatar shape="square" :src="text + '?x-oss-process=image/resize,w_50,h_50'"
                @click="text ? previewImgObject([text]) : () => { }"> </a-avatar>
            </span>
            <template slot="adjustQty" slot-scope="text, record">
              <div class="editable-cell" :key="'editcell_' + record.id" v-if="model.bizStatus === 1">
                <div v-if="editable['key_' + record.id]">
                  <a-input-number :min="0" :max="999999" style="width: 80px" :defaultValue="text"
                    @change="(number) => editCellHandleChange(number, record.id)"
                    @pressEnter="editCellCheck(record.id)" />
                  <a-icon type="check" @click="editCellCheck(record.id)" class="editable-cell-icon-check" />
                  <a-icon type="close" @click="handleEditCell(record.id, false)" class="editable-cell-icon" />
                </div>
                <div v-else>
                  {{ text }}
                  <a-icon type="edit" @click="handleEditCell(record.id, true)" class="editable-cell-icon" />
                </div>
              </div>
              <div v-else>
                {{ text }}
              </div>
            </template>
          </a-table>
          <a-table size="middle" v-else :columns="groupColumns" :dataSource="groupDataList" :pagination="false">
            <a-table style="margin: 1px" slot="expandedRowRender" slot-scope="record" :columns="goodsColumns"
              :dataSource="record.list" :pagination="false" size="middle" rowKey="id">
              <span slot="photo" slot-scope="text">
                <a-avatar shape="square" :src="text + '?x-oss-process=image/resize,w_50,h_50'"
                  @click="text ? previewImgObject([text]) : () => { }"> </a-avatar>
              </span>
            </a-table>
          </a-table>
        </a-card>
      </a-card>
    </a-spin>

    <!-- 表单区域 -->
    <SelectProductList ref="selectProdForm" @ok="selectOk"></SelectProductList>
  </j-modal>
</template>

<script>
import PageLayout from '@/components/page/PageLayout'
import STable from '@/components/table/'
import DetailList from '@/components/tools/DetailList'
import ABadge from 'ant-design-vue/es/badge/Badge'
import { getAction, postAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'
import SelectProductList from './SelectProductList'
const DetailListItem = DetailList.Item
import { previewImgObject } from '@/utils/util'
import { groupingData } from '@/utils/util'

export default {
  components: {
    PageLayout,
    ABadge,
    DetailList,
    DetailListItem,
    STable,
    SelectProductList,
  },
  name: 'PosStockReturnBillModal',
  data() {
    return {
      title: '操作',
      fullscreen: true,
      visible: false,
      previewImgObject,
      params: {},
      model: {},
      editable: {},
      editCellData: {},
      detailRespList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      tabList: [
        {
          key: '1',
          tab: '商品明细',
        },
        // {
        //   key: '2',
        //   tab: '付款明细',
        // },
      ],
      activeTabKey: '1',
      confirmLoading: false,
      submitLoading: false,
      validatorRules: {},
      groupingData,
      groupCol: 'default',
      groupDataList: [],
      groupColumns: [
        {
          title: '价位',
          align: 'left',
          dataIndex: 'markPrice',
        },
        {
          title: '签收件数',
          align: 'left',
          dataIndex: 'cnt',
          customRender: (text, record) => {
            return record.list.reduce((total, cur) => {
              return total + cur.adjustQty
            }, 0)
          },
        },
      ],
      goodsColumns: [
        {
          title: '商品图片',
          dataIndex: 'photo',
          align: 'center',
          scopedSlots: { customRender: 'photo' },
        },
        {
          title: 'SKU编码',
          dataIndex: 'itemSku',
          align: 'center',
        },
        {
          title: '商品名称',
          dataIndex: 'itemShortName',
          align: 'center',
        },
        {
          title: '颜色',
          dataIndex: 'itemColor',
          align: 'center',
        },
        {
          title: '尺码',
          dataIndex: 'itemSize',
          align: 'center',
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          align: 'center',
        },
        {
          title: '销售单价(元)',
          dataIndex: 'markPrice',
          align: 'center',
        },
        {
          title: '返货数量',
          dataIndex: 'ioQty',
          align: 'center',
        },
        {
          title: '签收数量',
          dataIndex: 'adjustQty',
          align: 'center',
          scopedSlots: { customRender: 'adjustQty' },
          width: '15%',
        },
        {
          title: '是否调整',
          dataIndex: 'adjusted',
          align: 'center',
          customRender: (text, record) => {
            //是否调整:0无调整 1修改 2添加 3删除
            if (text === 0) {
              return '-'
            }
            if (text === 1) {
              return '修改'
            }
            if (text === 2) {
              return '添加'
            }
            if (text === 3) {
              return '删除'
            }
          },
        },
      ],
      url: {
        detail: '/stock/posStockReturnBill/queryById',
        changeStatus: '/stock/posStockReturnBill/changeStatus',
        adjustQty: '/stock/posStockReturnBill/detail/adjustQty',
        changeStatusAndQty: '/stock/posStockReturnBill/changeStatusAndQty'
      },
    }
  },
  created() { },
  methods: {
    clear() {
      this.model = {}
      this.detailRespList = []
      this.activeTabKey = '1'

      this.groupCol = 'default'
      this.groupDataList = []
    },
    view(recordId) {
      this.visible = true
      this.detailInfo(recordId)
    },
    close() {
      this.$emit('close')
      this.clear()
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    detailInfo(recordId) {
      let that = this
      getAction(this.url.detail + '/' + recordId, this.params).then((res) => {
        if (res.success) {
          that.model = res.result
          let goodsItemList = that.model.detailRespList.sort((a, b) => Number(a.orgprice) - Number(b.orgprice))
          that.detailRespList = goodsItemList

          that.groupDataList = that.groupingData(goodsItemList, 'markPrice')

        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleStatus(state, url) {
      let that = this
      let params = { billId: this.model.id, bizStatus: state }
      this.submitLoading = true
      postAction(url, params).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.close()
          that.$emit('ok')
        } else {
          that.$message.warning(res.message)
        }
        that.submitLoading = false
      })
    },
    handleEditCell(id, isEdit) {
      console.log('id=', id, '--isEdit=', isEdit)
      this.$set(this.editable, 'key_' + id, isEdit)
    },
    editCellHandleChange(value, id) {
      console.log('value=', value, ',id=', id)
      this.editCellData = { id: id, adjustQty: value }
    },
    editCellCheck(id) {
      console.log('id=', id)
      if (!this.editCellData) {
        return
      }

      let that = this
      this.editable['key_' + id] = false
      let param = this.editCellData
      console.log('param=', param)

      postAction(this.url.adjustQty, param)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.detailInfo(that.model.id)
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          console.log('finally')
        })
    },
    doSign() {
      let that = this
      Modal.confirm({
        title: '确定签收吗?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK')
          that.handleStatus(2, that.url.changeStatus)
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    doRefuse() {
      let that = this
      Modal.confirm({
        title: '库存将会回退，确定驳回吗?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK')
          that.handleStatus(1, that.url.changeStatusAndQty)
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    newRow() {
      this.$refs.selectProdForm.search(this.model)
      this.$refs.selectProdForm.title = '选择商品'
      this.$refs.selectProdForm.visible = true
    },
    selectOk() {
      this.detailInfo(this.model.id)
    },
  },
}
</script>

<style lang="less" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  margin-left: 10px;
  cursor: pointer;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.table-operations {
  margin-bottom: 3px;

  .r-group {
    z-index: 999;
    text-align: right;
  }
}
</style>